﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using WebConsulClientTest.Models;
using System.Net.Http;
using Consul;
using System.Text.Json;
using MicroService.ConsulWebClientTest;

namespace WebConsulClientTest.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private readonly IHttpClientFactory httpClientFactory;

        private static int Seed = 0;


        private JsonSerializerOptions serializeOptions = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true,
            WriteIndented = true
        };

        public HomeController(ILogger<HomeController> logger, IHttpClientFactory _httpClientFactory)
        {
            _logger = logger;
            httpClientFactory = _httpClientFactory;
        }

        public IActionResult Index()
        {
            var url = GetServiceUrl();
            var token = new IdentityServerClient().GetToken().Result;
            var result = Get(url,null, token).Result;
            _logger.LogInformation(result);
            ViewBag.testString = result;
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }


        /// <summary>
        /// Get请求数据
        /// <para>最终以url参数的方式提交</para>
        /// </summary>        
        /// <param name="requestUri">例如/api/Files/UploadFile</param>
        /// <param name="parameters">参数字典,可为空</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<string> Get(string requestUri, Dictionary<string, string> parameters, string token)
        {
            //从工厂获取请求对象
            var client = httpClientFactory.CreateClient();
            //添加请求头
            if (!string.IsNullOrWhiteSpace(token))
            {
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            }
            //client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
            //拼接地址
            if (parameters != null)
            {
                var strParam = string.Join("&", parameters.Select(o => o.Key + "=" + o.Value));
                requestUri = string.Concat(requestUri, '?', strParam);
            }
            client.BaseAddress = new Uri(requestUri);
            return await client.GetStringAsync(requestUri);
        }

        public string GetServiceUrl()
        {
            string url = "http://MicroService.APIResource/api/Values/GetData";
            Uri uri = new Uri(url);
            string serviceName = uri.Host;

            ConsulClient client = new ConsulClient(options =>
            {
                options.Address = new Uri("http://localhost:8500");
                options.Datacenter = "dc1";
            });
           
            var dic = client.Agent.Services().Result.Response
                .Where(t => t.Value.Service.Equals(serviceName,StringComparison.OrdinalIgnoreCase));

            //添加权重功能
            List<AgentService> agents = new List<AgentService>();
            foreach (var keyvalue in dic)
            {
                var agentService = keyvalue.Value;
                Console.WriteLine($"{agentService.Address}-->{agentService.Port}-->{string.Join("|", agentService.Tags)}-->{agentService.Service}");

                var weight = int.Parse(agentService.Tags[0]);
                for(int i=0;i< weight;i++)
                {
                    agents.Add(agentService);
                }
            }
           
            var agent = agents[Seed++ % agents.Count];

            return $"{uri.Scheme}://{agent.Address}:{agent.Port}{uri.PathAndQuery}";
        }
    }
}
